const FenleiDao = require("../dao/fenlei_dao.js");

const FenleiService = {
    //添加数据
    add(req,res,next){
        //从请求主体中解构文本数据
        const{fenlei_name,fen} = req.body;
        //保存到数据库
        FenleiDao
            .save({fenlei_name,fen})
            .then(data=>{
                res.json({res_code:1,res_error:"",res_body:data})
            })
            .catch(err=>{
                res.json({res_code:-1,res_error:err,res_body:{}})
            });
    },
    //分页查询
    listByPage(req,res,next){
        //获取待查询的页码
        let{page}=req.query;
        page= page||1;
        //调用数据库查询方法
        FenleiDao
            .count()
            .then((data)=>{
                FenleiDao   
                    .findByPage(page)
                    .then(pageData=>{
                        //总页数
                        const totalPages = Math.ceil(data/10);
                        res.json({res_code:1,res_error:"",res_body:{data:pageData,count:data,totalPages}});
                    })
                    .catch(err=>{
                        res.json({res_code:-1,res_error:err,res_body:{}});
                    });
            })
            .catch(err=>{
                res.json({res_code:-1,res_error:err,res_body:{}});
            })
    },
    //修改
    update(req,res,next){
        const {id,fenlei_name,fen}=req.body;
        FenleiDao.update({id,fenlei_name,fen})
            .then((data)=>{
                res.json({res_code:1,res_error:"",res_body:data})
            })
            .catch(err=>{
                res.json({res_code:-1,res_error:err,res_body:{}});
            });
    },
    //删除
    remove(req,res,next){
        const {_id}=req.body;
        FenleiDao.delete({_id})
            .then((data)=>{
                res.json({res_code:1,res_error:"",res_body:data})
            })
            .catch(err=>{
                res.json({res_code:-1,res_error:err,res_body:{}});
            });
    }
}

module.exports = FenleiService;